package cn.ynrcb.personnelfile.sysadmin.service.impl;

import cn.ynrcb.personnelfile.admin.vo.OrgVo;
import cn.ynrcb.personnelfile.common.utils.PageUtils;
import cn.ynrcb.personnelfile.sysadmin.dao.SysOrgDao;
import cn.ynrcb.personnelfile.sysadmin.dao.SysRegionDao;
import cn.ynrcb.personnelfile.sysadmin.dao.SysUserDao;
import cn.ynrcb.personnelfile.sysadmin.entity.SysOrgEntity;
import cn.ynrcb.personnelfile.sysadmin.service.CurrentUserService;
import cn.ynrcb.personnelfile.sysadmin.service.SysOrgService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service("sysOrgService")
public class SysOrgServiceImpl extends ServiceImpl<SysOrgDao, SysOrgEntity> implements SysOrgService {

    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private CurrentUserService currentUserService;
    @Autowired
    private SysRegionDao sysRegionDao;

    @Override
    public String generateInnerCode(SysOrgEntity org) {
        String inner_code = "";
        if (new Long("0").equals(org.getPId())) {
            long code = baseMapper.getCountByPId(Long.valueOf(0));
            code = 1000 + code + 1;
            inner_code = String.valueOf(code);
        } else {
            SysOrgEntity parent = baseMapper.findByOrgId(org.getPId());
            long sameLevelSize = baseMapper.getCountByPId(org.getPId());
            inner_code = parent.getInnerCode() + (1000 + sameLevelSize + 1);
        }
        return inner_code;
    }

    @Override
    public void saveOrg(SysOrgEntity sysOrg) {
        sysOrg.setInnerCode(generateInnerCode(sysOrg));
        save(sysOrg);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Page<SysOrgEntity> page = new Page<SysOrgEntity>(Long.valueOf(params.get("page") + ""), Long.valueOf(params.get("limit") + ""));
        List<SysOrgEntity> list = baseMapper.querySysOrgPage(page, params);
        page.setRecords(list);
        PageUtils pageData = new PageUtils((IPage<?>) page);
        return pageData;
    }

    @Override
    public void updateStatusByIds(List<Integer> ids) {
        baseMapper.updateStatusByIds(ids);
    }

    @Override
    public JSONArray treeData(Integer pid) {
//        SysOrgEntity org = baseMapper.findByOrgId((pid == 0 || pid == null) ? 1:pid);
//        List<SysOrgEntity> orgList = baseMapper.findByInnerCode(org.getInnerCode());
        List<SysOrgEntity> orgList = baseMapper.findByPid(pid);
        if (CollectionUtils.isNotEmpty(orgList)) {
            JSONArray arr = converToTreeNode(orgList);
            for (int i = 0; i < arr.size(); i++) {
                JSONObject obj = arr.getJSONObject(i);
//				obj.put("children", treeData(obj.getIntValue("id")));
                obj.put("leaf", baseMapper.getCountByPId(obj.getLongValue("id")) != 0 ? false : true);
            }
            return arr;
        }
        return null;
    }

    public JSONArray converToTreeNode(List<SysOrgEntity> list) {
        JSONArray arr = new JSONArray();
        if (CollectionUtils.isNotEmpty(list)) {
            JSONObject obj = null;
            for (SysOrgEntity org : list) {
                obj = new JSONObject();
                obj.put("label", org.getOrgName());
                obj.put("id", org.getId());
                obj.put("code", org.getInnerCode());
                arr.add(obj);
            }
            return arr;
        }
        return null;
    }

    @Override
    public List<SysOrgEntity> orgAndUserTree() {
        List<SysOrgEntity> orgUserList = baseMapper.orgAndUserTree();//获得用户和机构的数据
        HashMap<String, SysOrgEntity> mapList = new HashMap<>();
        if (CollectionUtils.isNotEmpty(orgUserList)) {
            for (SysOrgEntity orgUser : orgUserList) {//将所有数据都放入一个map中，后续通过从map中取值看是否有父节点
                mapList.put(orgUser.getUid(), orgUser);
            }
        }
        List<SysOrgEntity> orgUserResultArr = new ArrayList<>();//最终返回的结果
        if (CollectionUtils.isNotEmpty(orgUserList)) {
            for (SysOrgEntity orgUser : orgUserList) {
                // 我们在存储的时候就是将元素的id为键，元素本身为值存入的
                // 以元素的父id为键，在map里取值，若取不到则，对应的元素不存在，即没有父节点，为顶层节点或游离节点
                SysOrgEntity parent = mapList.get(orgUser.getParentId().toString());
                if (parent != null) {//有父节点，当前结点为子节点
                    if (parent.getChildren() == null) {//chidren 若为第一次必须new 一个数组再添加
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(orgUser);//这个操作是引用操作，所以map和resultList中sysOrgEntity都已经修改了
                } else {// 无父节点，将顶层节点放入resultList集合
                    orgUserResultArr.add(orgUser);
                }
            }
        }
        return orgUserResultArr;
    }

    @Override
    public int childCount(List<Integer> asList) {
        return baseMapper.childCount(asList);
    }

    @Override
    public List<SysOrgEntity> queryOrgTree() {
        return baseMapper.queryOrgTree();
    }

    @Override
    public String getAssociation(Long orgId) {
        return baseMapper.getOrgNameByOrgId(Math.toIntExact(orgId));
    }


    @Override
    public List<OrgVo> findOrg() {
        return baseMapper.findOrg();
    }

    @Override
    public Boolean updateOrg(SysOrgEntity sysOrg) {
        return baseMapper.updateOrg(sysOrg);
    }
}
